import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl/login';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
    // 登录
   async login (username: string, password: string) {
      try {
        // 发请求登录,成功会有token
        let result = await reqLogin({username,password})
        // 仓库存储token
        this.token = result.token
        // 持久化存储token
        setToken(result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
 async   getInfo () {
      try {
        // 登录成功获取用户信息,请求头带token
        let result = await reqUserInfo()
        // 获取数据存储
        this.name = result.name
        this.avatar = result.avatar
        this.menuRoutes = staticRoutes
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },

  async  reset () {
  try {
    await reqLogOut()
        // 删除local中保存的token
        removeToken()
        // 提交重置用户信息的mutation
        this.token = ''
        this.name = ''
        this.avatar = ''
        return 'ok'
  } catch (error) {
    return Promise.reject(error)
  }
    },
	},
});
